package com.example.randox;


import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import library.DatabaseHandler;
import library.UserFunctions;

import com.example.technics.Utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class LoginActivity extends Activity {
	
	// JSON Response node names
    private static String KEY_SUCCESS = "success";
    private static String KEY_ERROR = "error";
    private static String KEY_IDUSER = "idUser";
    private static String KEY_FIRSTNAME = "firstname";
    private static String KEY_EMAIL = "email";
    private static String KEY_IDSTATUS = "idStatus";
    private static String KEY_IDCONVERSATION = "idConversation";
    private static String KEY_SEX = "sex";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);
		
		 final EditText email = (EditText)findViewById(R.id.editText1);
		 final EditText password = (EditText)findViewById(R.id.editText2);
		 
		 TextView login = (TextView)findViewById(R.id.button1);
		 
		 TextView signUp = (TextView)findViewById(R.id.signUp);
		 
		 final List<EditText> ListFields = new ArrayList<EditText>(){{
			 add(email);
			 add(password);
		 }};
		 
		 
		 login.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
						boolean fieldEmpty=false;
						boolean errors=false;
			    		 for (EditText field : ListFields) {
			    			    if(TextUtils.isEmpty(field.getText().toString())){
			    			    	field.requestFocus();
					    		 	field.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_error, 0);
					    			if(!fieldEmpty==true){
		    			    			Toast.makeText(LoginActivity.this, "Please complete all fields", Toast.LENGTH_SHORT).show();
		    			    		}
					    		 	fieldEmpty=true;
					    		 	errors=true;	
			    			    }else{
			    			    	if(field==email){
			    			    		if(Utils.isEmailValid(field.getText().toString())==false){
			    			    			field.requestFocus();
			    			    			field.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_error, 0);
			    			    			Toast.makeText(LoginActivity.this, "Please enter a valid email", Toast.LENGTH_SHORT).show(); 
			    			    			errors=true;
			    			    		}else{
			    			    			field.requestFocus();
			    			    			field.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
			    			    		}
			    			    	}else{
			    			    		
			    			    	}
			    			    }
			    			}
			    		 
			    		 
			    		 //TRAITEMENT DU LOGIN
			    		 
			    		 if(errors==false){
			    			
			    			//CHARGEMENT
			    			ProgressDialog progress=new ProgressDialog(LoginActivity.this); 
			    			progress.setCancelable(true);
			    			progress.setMessage("Loading ....");
			    			progress.show();
			    			
			    			UserFunctions userFunction = new UserFunctions();
			                JSONObject json = userFunction.loginUser(email.getText().toString(), password.getText().toString());
			                 
			                  try {
			                     if (json.getString(KEY_SUCCESS) != null) {
			                         String res = json.getString(KEY_SUCCESS); 
			                         if(Integer.parseInt(res) == 1){
			                             DatabaseHandler db = new DatabaseHandler(getApplicationContext());
			                             JSONObject json_user = json.getJSONObject("user");
			                             userFunction.logoutUser(getApplicationContext());
			                             db.addUser(json_user.getInt(KEY_IDUSER),json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_EMAIL), json_user.getInt(KEY_IDSTATUS),json_user.getInt(KEY_IDCONVERSATION),json_user.getString(KEY_SEX));
			                             
			                             
			                             JSONObject jsonCheck = userFunction.checkConversation(json_user.getString(KEY_EMAIL));
			                	         	try {
			                               if (jsonCheck.getString(KEY_SUCCESS) != null) {
			                                   String resChek = jsonCheck.getString(KEY_SUCCESS); 
			                                   if(Integer.parseInt(resChek) == 1){  
			                                   		Intent i=new Intent(LoginActivity.this,ChatActivity.class);
			                                   		i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
			                                   		startActivity(i);
			                                   		finish();
			                                   }else{
			                                   		Intent i=new Intent(LoginActivity.this,MemberActivity.class);
			                                   		i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
			                                   		startActivity(i);
			                                   		finish();
			                                   }
			                               }
			                	         	} catch (JSONException e) {
			                         	  e.printStackTrace();
			                           	}
			                             
			                             
			                         }else{
			                        	 progress.cancel();
			                        	 Toast.makeText(LoginActivity.this, "Invalid login, please try again", Toast.LENGTH_SHORT).show();
			                        	 email.requestFocus();
			                        	 password.requestFocus();
			    			    		 email.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_error, 0);
			    			    		 password.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_error, 0);
			                         }
			                     }
			                 } catch (JSONException e) {
			                     e.printStackTrace();
			                 }
			             
			                 
			    		 }
			    }
			});
		 
		 
			signUp.setOnClickListener(new View.OnClickListener() {
			    public void onClick(View v) {
			        Intent i=new Intent(LoginActivity.this,RegisterActivity.class);
			        i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    startActivity(i);
                    finish();
			    }
			});
	}





}
